package com.eqdd.yiqidian.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputConnectionWrapper;

/**
 * Created by lv on 17-9-11.
 */

public class WatchDeleteKeyEditText extends android.support.v7.widget.AppCompatEditText {

    private OnKeyListener keyListener;

    public WatchDeleteKeyEditText(Context context) {
        super(context);
    }

    public WatchDeleteKeyEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public WatchDeleteKeyEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    //覆盖输入框和键盘的关联接口
    @Override
    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {

        return new MyInputConnection(super.onCreateInputConnection(outAttrs),
                true);
    }


    private class MyInputConnection extends InputConnectionWrapper {

        InputConnection inputConnection;

        public MyInputConnection(InputConnection target, boolean mutable) {
            super(target, mutable);
            inputConnection = target;
        }

        //覆盖事件传递
        @Override
        public boolean sendKeyEvent(KeyEvent event) {
            if (keyListener != null) {
                keyListener.onKey(WatchDeleteKeyEditText.this, event.getKeyCode(), event);
            }
            return super.sendKeyEvent(event);
        }

        @Override
        public boolean deleteSurroundingText(int beforeLength, int afterLength) {
            //在删除时，输入框无内容，或者删除以后输入框无内容
            if ( afterLength == 0 || beforeLength == 0||beforeLength==1) {
                // backspace
                return sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL))
                        ;
            }
            return super.deleteSurroundingText(beforeLength, afterLength);
        }

        @Override
        public boolean finishComposingText() {

            return true;
        }

    }

    //设置监听回调
    public void setWatchDeleteEvent(OnKeyListener listener) {
        keyListener = listener;
    }

}
